﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Text;
using System.Threading.Tasks;

namespace Developer.Core.FrameWork.Common.Results
{
    /// <summary>
    /// 前台页面通用结果包装器
    /// </summary>
    public class PageResultWapper : IAsyncResultFilter
    {
        public Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            throw new NotImplementedException();
        }

        private object WapperSuccessResult(object value)
        {
            dynamic warpResult = new ExpandoObject();
            warpResult.Success = "true";
            warpResult.ErrorInfo = "";

            if (value.GetType().Name.Contains("List"))
            {
                warpResult.ResultList = new JsonResult(value).Value;
            }
            else if(value.GetType().Name.Contains("Dictionary"))
            {
                IDictionary dictionary = (IDictionary)value;
                if (dictionary.Contains("ErrorInfo"))
                {
                    warpResult.Success = dictionary["Success"];
                    warpResult.ErrorInfo = dictionary["ErrorInfo"];

                    dictionary.Remove("Success");
                    dictionary.Remove("ErrorInfo");
                }
            }
            else
            {
                warpResult.ResultDic = new JsonResult(value).Value;
            }

            return warpResult;
        }

        private object WapperFaildResult(ObjectResult value)
        {
            dynamic warpResult = new ExpandoObject();
            warpResult.Success = value.StatusCode;

            if (value.Value is string info)
                warpResult.ErrorInfo = info;
            else
                warpResult.ErrorInfo = new JsonResult(value.Value).Value;

            return warpResult;
        }
    }
}
